require 'middleman-core/util'

module Middleman
  module Org

    class OrgData
      attr_reader :options
      attr_reader :controller

      def initialize(app, controller, options)
        @app = app
        @options = options
        @controller = controller

        @_articles = []
      end

      def articles
        @_articles
      end

      def tags
        []
      end

      def manipulate_resource_list(resources)
        @_posts = []
        article_hash = {}
        resources.each do |resource|
          next unless resource.path =~ /^#{options.root}/
          if resource.path.include?("/meta/")

          else
            resource.destination_path = resource.path.gsub(/.html/,"/index.html")  # RESTFUL
            if File.extname(resource.source_file) == '.org'
              article = convert_to_article resource
              next unless publishable?(article)
              @_articles << article
              article_hash[article.path] = article
            end
          end
        end
        # 先遍历文章, 再遍历 meta 数据
        resources.each do |resource|
          next unless resource.path =~ /^#{options.root}/
          if resource.path.include?("/meta/")
            # binding.pry
            meta_hash = JSON.parse(File.open(resource.source_file).read)
            article_hash
            # binding.pry
            key = resource.path.sub('meta/','').sub('.json','.html')
            # binding.pry
            article_hash[key].set_meta_data('title', meta_hash['title'])
            article_hash[key].set_meta_data('date', meta_hash['date'])
            article_hash[key].set_meta_data('summary', meta_hash['summary'])
          else

          end
        end

        # 排序
        # @_articles.sort! { |a, b| a.get_meta_data('date') <=> b.get_meta_data('date') }
      end

      def publishable?(article)
        @app.environment == :development || article.published?
      end

      def convert_to_article(resource)
        return resource if resource.is_a?(OrgArticle)
        resource.extend OrgArticle
        resource.org_controller = controller
        resource
      end

    end
  end
end
